const http = require('http')
const url = require('url')


function createApp() {
  return new App()
}


function App() {
  // 路由表
  this.routes = []
}

App.prototype.get = function (path, handler) {
  this.routes.push({
    path,
    method: 'get',
    handler
  })
}


App.prototype.post = function (path, handler) {
  this.routes.push({
    path,
    method: 'get',
    handler
  })
}

App.prototype.listen = function (...args) {
  http.createServer((req, res) => {
    // 可以自动适配响应体的数据
    res.send = function (data) {
      // [object Object] [object Array]
      // console.log(Object.prototype.toString.call(data))
      // console.log({}.toString.call(data))
      if (typeof data == 'object') {
        if ((data instanceof Object || Array.isArray(data)) && !(data instanceof Buffer)) {
          res.setHeader('content-type', 'application/json;charset=utf-8')
          res.end(JSON.stringify(data))
        } else {
          res.setHeader('content-type', 'text/html;charset=utf-8')
          res.end(data)
        }
      } else if (typeof data == 'string') {
        res.setHeader('content-type', 'text/html;charset=utf-8')
        res.end(data)
      } else {
        res.end(data + '')
      }
    }

    let { pathname, query } = url.parse(req.url, true)
    req.query = query
    let method = req.method.toLowerCase()

    let route = this.routes.find(route => {
      if (route.method == method && route.path == pathname) {
        return route
      }
    })
    if (route) {
      route.handler(req, res)
      return;
    }

    res.end('404')

  }).listen(...args)
}


module.exports = createApp
